#include "memmonitor.h"

Memmonitor::Memmonitor(QObject *parent) : QObject(parent) 
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Memmonitor::updateMemUsage);
    timer->start(1000);
}

Memmonitor::~Memmonitor() 
{
    if (timer != nullptr)
    {
        if (timer->isActive())
        {
            timer->stop();
        }
    }
}

QString Memmonitor::getMemUsage() {
    FILE* file = popen("cat /proc/meminfo", "r");
    if (!file)
        return "Error: Cannot open /proc/meminfo";

    QTextStream in(file);
    QString line;
    qlonglong totalMem = 0;
    qlonglong freeMem = 0;
    qlonglong buffers = 0;
    qlonglong cached = 0;

    while (!in.atEnd()) {
        line = in.readLine();
        if (line.startsWith("MemTotal:")) {
            totalMem = line.split(QRegExp("\\s+"))[1].toLongLong();
        } else if (line.startsWith("MemFree:")) {
            freeMem = line.split(QRegExp("\\s+"))[1].toLongLong();
        } else if (line.startsWith("Buffers:")) {
            buffers = line.split(QRegExp("\\s+"))[1].toLongLong();
        } else if (line.startsWith("Cached:")) {
            cached = line.split(QRegExp("\\s+"))[1].toLongLong();
        }
    }

    qlonglong usedMem = totalMem - freeMem - buffers - cached;
    double usage = (double)usedMem / totalMem * 100;
    pclose(file);
    return QString::number(usage, 'f', 2) + "%";
}

void Memmonitor::updateMemUsage() {
    emit memChanged();
}

